#include "threshold.hh"

ApplyThresh::ApplyThresh (IplImage* input_,
			  unsigned thresh_)
  : input(input_),
    thresh(thresh_)
{
  output = cvCreateImage (cvSize (input->width, input->height), IPL_DEPTH_8U, 3); 
  thresh = 3 * thresh;
}

void ApplyThresh::operator() (const tbb::blocked_range2d<int>& r) const
{
  for (int i = r.rows().begin(); i!= r.rows().end(); ++i)
    for (int j = r.cols().begin(); j!= r.cols().end(); ++j)
      {
	CvScalar s = cvGet2D (input, i, j);
	unsigned mean = s.val[0] + s.val[1] + s.val[2];
	if (mean > thresh)
	  {
	    s.val[0] = 255;
	    s.val[1] = 255;
	    s.val[2] = 255;
	  }
	else
	  {
	    s.val[0] = 0;
	    s.val[1] = 0;
	    s.val[2] = 0;
	  }
	cvSet2D (output, i, j, s);
      }
}

IplImage*
ApplyThresh::getOutput ()
{
  return output;
}

IplImage*
threshold (IplImage* input,
	   unsigned thresh)
{
  ApplyThresh app(input, thresh);
  tbb::parallel_for(tbb::blocked_range2d<int>(0,input->height, 0,input->width),
                    app, tbb::auto_partitioner());

  return app.getOutput ();
}
